<?php

namespace Gaolei\YiiRBAC\models\form;

use Yii;
use yii\base\Model;
use Gaolei\YiiRBAC\models\Adminer;
use yii\helpers\ArrayHelper;

/**
 * Signup form
 */
class Signup extends Model
{
    public $username;
    public $realname;
    public $password;
    public $phone;
    public $level;

    /**
     * @inheritdoc
     */
    public function rules(): array
    {
        $class = Yii::$app->getUser()->identityClass ?: Adminer::class;
        return [
            [['username', 'realname'], 'filter', 'filter' => 'trim'],
            ['username', 'required', 'message' => '用户名不可以为空'],
            ['username', 'match', 'pattern' => '/^[0-9A-Za-z]{2,20}$/', 'message' => '用户名只能由字母与数字组成，且长度在2~20之间'],
            ['realname', 'required', 'message' => '真实姓名不可以为空'],
            ['username', 'unique', 'targetClass' => $class, 'message' => '用户名已存在.'],
            ['realname', 'unique', 'targetClass' => $class, 'message' => '管理员已存在.'],
            ['realname', 'string', 'min' => 2, 'max' => 12],
            ['phone', 'required', 'message' => '联系电话不能为空！'],
            ['phone', 'match', 'pattern' => '/^1[3-9]\d{9}$/', 'message' => '手机号格式不正确！'],
            ['phone', 'unique', 'targetClass' => $class, 'message' => 'phone 已经被使用了.'],
            ['level', 'integer'],
            ['password', 'required', 'message' => '密码不可以为空'],
            ['password', 'string', 'min' => 6, 'tooShort' => '密码至少填写6位'],
        ];
    }

    /**
     * Signs user up.
     * @return Adminer|null the saved model or null if saving fails
     * @throws \yii\base\Exception
     */
    public function signup()
    {
        if ($this->validate()) {
            $class = Yii::$app->getUser()->identityClass ?: Adminer::class;
            $user = new $class();
            $user->username = $this->username;
            $user->realname = $this->realname;
            $user->phone = $this->phone;
            $user->level = $this->level;
            $user->state = ArrayHelper::getValue(Yii::$app->params, 'rbac.admin.defaultStatus', Adminer::STATE_ACTIVE);
            $user->setPassword($this->password);
            $user->generateAuthKey();
            $user->created_at = $user->updated_at = time();
            if ($user->save()) {
                return $user;
            }
        }
        return null;
    }
}
